import * as vscode from 'vscode'
import { CompatibilityTree } from '../compatibility-tree'

/**
 * VS Code扩展实现
 * 提供实时代码分析和安全检测
 */
export function activateVSCodeExtension(tree: CompatibilityTree) {
  // 注册代码诊断器
  const diagnosticCollection = vscode.languages.createDiagnosticCollection('compatibility')
  
  // 监听文档保存事件
  vscode.workspace.onDidSaveTextDocument(document => {
    analyzeDocument(document, diagnosticCollection, tree)
  })

  // 初始分析所有打开文档
  vscode.workspace.textDocuments.forEach(doc => {
    analyzeDocument(doc, diagnosticCollection, tree)
  })
}

/**
 * 分析文档内容
 */
async function analyzeDocument(
  document: vscode.TextDocument,
  collection: vscode.DiagnosticCollection,
  tree: CompatibilityTree
) {
  const diagnostics: vscode.Diagnostic[] = []
  
  // 1. 代码规范检查
  const pep8Issues = checkPEP8Compliance(document)
  diagnostics.push(...pep8Issues)

  // 2. 安全漏洞检测
  const securityIssues = detectSecurityVulnerabilities(document, tree)
  diagnostics.push(...securityIssues)

  // 3. 兼容性检查
  const compatibilityIssues = checkCompatibility(document, tree)
  diagnostics.push(...compatibilityIssues)

  collection.set(document.uri, diagnostics)
}

/**
 * PEP8规范检查
 */
function checkPEP8Compliance(document: vscode.TextDocument): vscode.Diagnostic[] {
  const issues: vscode.Diagnostic[] = []
  const text = document.getText()
  
  // 检查行长度
  const lines = text.split('\n')
  lines.forEach((line, i) => {
    if (line.length > 79) {
      const range = new vscode.Range(i, 0, i, line.length)
      issues.push(
        new vscode.Diagnostic(
          range,
          '行长度超过79字符(PEP8 E501)',
          vscode.DiagnosticSeverity.Warning
        )
      )
    }
  })

  // 检查缩进
  if (text.includes('\t')) {
    const firstTabPos = text.indexOf('\t')
    const line = text.substring(0, firstTabPos).split('\n').length - 1
    const range = new vscode.Range(line, 0, line, 1)
    issues.push(
      new vscode.Diagnostic(
        range,
        '使用制表符而不是空格缩进(PEP8 W191)',
        vscode.DiagnosticSeverity.Warning
      )
    )
  }

  return issues
}

/**
 * 安全漏洞检测
 */
function detectSecurityVulnerabilities(
  document: vscode.TextDocument,
  tree: CompatibilityTree
): vscode.Diagnostic[] {
  const issues: vscode.Diagnostic[] = []
  const text = document.getText()
  
  // SQL注入检测
  const sqlRegex = /(?:execute|query)\([^)]*(?:\+\s*[a-zA-Z_$][\w$]*)+[^)]*\)/g
  let match: RegExpExecArray | null
  while ((match = sqlRegex.exec(text))) {
    const line = text.substring(0, match.index).split('\n').length - 1
    const lineText = text.split('\n')[line]
    const colStart = lineText.indexOf(match[0])
    const colEnd = colStart + match[0].length
    
    issues.push(
      new vscode.Diagnostic(
        new vscode.Range(line, colStart, line, colEnd),
        '潜在的SQL注入风险: 避免直接拼接SQL查询',
        vscode.DiagnosticSeverity.Error
      )
    )
  }

  // 不安全函数检测
  const dangerousFunctions = ['eval', 'exec', 'setTimeout', 'setInterval']
  dangerousFunctions.forEach(func => {
    const funcRegex = new RegExp(`\\b${func}\\([^)]*\\)`, 'g')
    while ((match = funcRegex.exec(text))) {
      const line = text.substring(0, match.index).split('\n').length - 1
      const lineText = text.split('\n')[line]
      const colStart = lineText.indexOf(match[0])
      const colEnd = colStart + match[0].length
      
      issues.push(
        new vscode.Diagnostic(
          new vscode.Range(line, colStart, line, colEnd),
          `不安全的函数调用: ${func}`,
          vscode.DiagnosticSeverity.Warning
        )
      )
    }
  })

  return issues
}

/**
 * 兼容性检查
 */
export function checkCompatibility(
  document: vscode.TextDocument,
  tree: CompatibilityTree
): vscode.Diagnostic[] {
  const issues: vscode.Diagnostic[] = []
  const text = document.getText()

  // 检查依赖导入
  const importRegex = /(?:import|require)\(?['"]([^'"]+)['"]\)?/g
  let match: RegExpExecArray | null
  while ((match = importRegex.exec(text))) {
    const pkgName = match[1].split('/')[0] // 获取主包名
    const line = text.substring(0, match.index).split('\n').length - 1
    const lineText = text.split('\n')[line]
    const colStart = lineText.indexOf(match[0])
    const colEnd = colStart + match[0].length

    // 检查兼容性
    if (!tree.isPackageCompatible(pkgName)) {
      issues.push(
        new vscode.Diagnostic(
          new vscode.Range(line, colStart, line, colEnd),
          `不兼容的依赖: ${pkgName} 不在兼容列表中`,
          vscode.DiagnosticSeverity.Error
        )
      )
    }
  }

  // 检查API使用
  const apiUsageRegex = /([a-zA-Z_$][\w$]*)\.([a-zA-Z_$][\w$]*)/g
  while ((match = apiUsageRegex.exec(text))) {
    const [fullMatch, obj, method] = match
    const line = text.substring(0, match.index).split('\n').length - 1
    const lineText = text.split('\n')[line]
    const colStart = lineText.indexOf(fullMatch)
    const colEnd = colStart + fullMatch.length

    // 检查API兼容性
    if (!tree.isApiCompatible(obj, method)) {
      issues.push(
        new vscode.Diagnostic(
          new vscode.Range(line, colStart, line, colEnd),
          `不兼容的API调用: ${obj}.${method}`,
          vscode.DiagnosticSeverity.Warning
        )
      )
    }
  }

  return issues
}